package com.yuanchu.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanchu.auth.dao.*;
import com.yuanchu.auth.entity.*;
import com.yuanchu.auth.service.YoshopStoreUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;


@Service("yoshopStoreUserService")
public class YoshopStoreUserServiceImpl extends ServiceImpl<YoshopStoreUserDao, YoshopStoreUserEntity> implements YoshopStoreUserService {

    @Resource
    private YoshopStoreUserRoleDao storeUserRoleDao;
    @Resource
    private YoshopStoreRoleDao storeRoleDao;
    @Resource
    private YoshopStoreMenuDao storeMenuDao;
    @Resource
    private YoshopStoreRoleMenuDao storeRoleMenuDao;

    /**
     * todo 根据用户id查询用户权限
     * @param userId
     * @return
     */
    public List<String> queryPermissions(String userId) {
        Set<String> list = new TreeSet<>();
        // 查询用户角色
        YoshopStoreUserRoleEntity storeUser = storeUserRoleDao.selectOne(new QueryWrapper<YoshopStoreUserRoleEntity>().eq("store_user_id", userId));
        YoshopStoreRoleEntity roleEntity = storeRoleDao.selectById(storeUser.getRoleId());
        String code = roleEntity.getCode();
        list.add("ROLE_" + code);
        // 根据角色id获取角色对应权限
        List<YoshopStoreRoleMenuEntity> menuEntities = storeRoleMenuDao.selectList(new QueryWrapper<YoshopStoreRoleMenuEntity>().eq("role_id", roleEntity.getRoleId()));
        List<Integer> mennuIds = menuEntities.stream().map(menu -> menu.getMenuId()).collect(Collectors.toList());
        if (!mennuIds.isEmpty()) {
            // 根据菜单id获取菜单
            List<YoshopStoreMenuEntity> menuEntities1 = storeMenuDao.selectBatchIds(mennuIds);
            menuEntities1.forEach(menu -> {
                if (StringUtils.isNotEmpty(menu.getActionMark())){
                    list.add(menu.getActionMark());
                }
            });
        }
        List<String> Prelist = new ArrayList<>(list);
        String[] stringArray = list.toArray(new String[0]);
        return Prelist;
    }


}